package com.godme.rabbitmq.repo;


import com.godme.rabbitmq.bean.Product;
import com.godme.rabbitmq.utils.SequenceGenerator;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class ProductRepository {

    private static final Map<String, Product> goods = new ConcurrentHashMap<>();


    @PostConstruct
    public void initProduct(){
        Product product = new Product();
        product.setName("性感口罩");
        product.setResidue(100);
        addProduct(product);
    }


    public Product findById(String id){
        if(goods.containsKey(id)){
            return goods.get(id);
        }
        return null;
    }


    public Product findByName(String name){
        for(Product product: goods.values()){
            if(product.getName().equals(name)){
                return product;
            }
        }
        return null;
    }

    public void addProduct(Product product){
        if(goods.values().stream().anyMatch(e->e.getName().equals(product.getName()))){
            return;
        }
        String id;
        do{
            id = SequenceGenerator.generateSequence();
        }while (goods.containsKey(id));
        product.setId(id);
        goods.put(id, product);
    }


    public void update(Product product){
        goods.put(product.getId(), product);
    }


    public void removeProduct(String id){
        if(goods.containsKey(id)){
            goods.remove(id);
        }
    }

    public void changeResidue(String productId, Integer delta){
        Product product = findById(productId);
        product.setResidue(product.getResidue() + delta);
    }


    public List<Product> findAll(){
        return new ArrayList<>(goods.values());
    }
}
